package com.s63.service.impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.s63.entity.Role;
import com.s63.mapper.RoleMapper;
import com.s63.service.IRoleService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.concurrent.TimeUnit;

@Service
public class RoleServiceImpl extends ServiceImpl<RoleMapper, Role> implements IRoleService {
    @Autowired
    private StringRedisTemplate stringRedisTemplate;
    @Autowired
    private ObjectMapper objectMapper;

    @Override
    public List<Role> list() {
        try {
            // 从缓存中找
            String roleList = stringRedisTemplate.opsForValue().get("roleList");
            if (roleList == null) {
                System.out.println("从数据库查询角色列表");
                List<Role> list = super.list();
                roleList = objectMapper.writeValueAsString(list);
                stringRedisTemplate.opsForValue().set("roleList", roleList, 5, TimeUnit.MINUTES);
            } else {
                System.out.println("从缓存中获取角色列表");
            }
            return objectMapper.readValue(roleList, List.class);
        } catch (JsonProcessingException e) {
            throw new RuntimeException(e);
        }
    }
}
